package org.EmploiDuTemps;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.GregorianCalendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;

public class DownloadBackground extends AsyncTask<Object, Integer, Week> {

	private String session;
	private int section;
	private Core core;
	
	
	@Override
	protected Week doInBackground(Object... param) {
		Integer weekNumber = (Integer) param[0];
		this.session = (String) param[1];
		this.section = (Integer) param[2];
		core = (Core) param[3];
		
		//Log.v("test","creation Semaine " + weekNumber + " - "+core.getContext().getClass());
		Week week = new Week(weekNumber, section);
		GregorianCalendar lastUpdate = week.getLastUpdate();
		lastUpdate.setTimeInMillis(System.currentTimeMillis());
		for (int i = 0; i<5; i++){
			Day day = getDay(i, weekNumber, week);
			//if (day == null) return null;
			week.addDay(day);
		}

		return week;
	}
	
	public Day getDay(int dayNumber, int weekNumber, Week week){
		Day day = new Day(dayNumber, weekNumber, week);
		GregorianCalendar date = day.getDate();
		
		weekNumber = weekNumber - 32;
		if (weekNumber <= 0) weekNumber += 52;
		
		try {
			Document doc = getPage("http://ade52-savoie.grenet.fr/ade/webapi?sessionId="+session+"&function=getEvents&resources="+section+"&detail=0&weeks="+weekNumber+"&days="+dayNumber);
			NodeList events = doc.getElementsByTagName("event");
			
			day.setNbCours(events.getLength());
			for (int i =0; i< events.getLength(); i++){
				 Node node = events.item(i);
				 NamedNodeMap attributes = node.getAttributes();
				 
				 Cour c = new Cour();
				 c.setActivityID(Long.parseLong(attributes.getNamedItem("activityId").getNodeValue()));
				 c.setName(attributes.getNamedItem("name").getNodeValue());
				 c.setDuration(Integer.parseInt(attributes.getNamedItem("duration").getNodeValue()));
				 
				 String colorString = attributes.getNamedItem("color").getNodeValue();
				 int rouge = Integer.parseInt(colorString.substring(0, colorString.indexOf(',')));
				 colorString = colorString.substring(colorString.indexOf(',')+1);
				 int vert = Integer.parseInt(colorString.substring(0, colorString.indexOf(',')));
				 colorString = colorString.substring(colorString.indexOf(',')+1);
				 int bleu = Integer.parseInt(colorString.substring(0));
				 
				 c.setColor(Color.rgb(rouge, vert,bleu));
				 
				 int debut = Integer.parseInt(attributes.getNamedItem("slot").getNodeValue())*15+(7*60+30);
				 int fin = debut + c.getDuration()*15;
				 
				 GregorianCalendar dateDebut = (GregorianCalendar) date.clone();
				 dateDebut.set(GregorianCalendar.HOUR_OF_DAY, debut/60);
				 dateDebut.set(GregorianCalendar.MINUTE, debut%60);
				 c.setStartTime(dateDebut);
				 
				 GregorianCalendar dateFin = (GregorianCalendar) date.clone();
				 dateFin.set(GregorianCalendar.HOUR_OF_DAY, fin/60);
				 dateFin.set(GregorianCalendar.MINUTE, fin%60);
				 c.setEndTime(dateFin);
				 
				 NodeList ressources = node.getChildNodes().item(1).getChildNodes();

				 for (int j = 0; j < ressources.getLength(); j++){
					 if (ressources.item(j).hasAttributes()){
						 if (ressources.item(j).getAttributes().getNamedItem("category").getNodeValue().equals("instructor"))
							 c.setProf(ressources.item(j).getAttributes().getNamedItem("name").getNodeValue());
						 if (ressources.item(j).getAttributes().getNamedItem("category").getNodeValue().equals("classroom"))
							 c.setRoom(ressources.item(j).getAttributes().getNamedItem("name").getNodeValue());
					 }
				 }
				 day.addDay(c);
			 }
			 
				 
		} catch (Exception e) {
			Log.e("test", "error jour : "+e.getMessage());
			day.setNbCours(-100);
		}
		return day;
	}
	
	public Document getPage(String url){
		try { 
			URL urlFormat = new URL(url);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			URLConnection conn = urlFormat.openConnection();
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			return db.parse(conn.getInputStream());
			
		} catch (MalformedURLException me) { 
			Log.e("error", "URL error :"+me.getMessage());
		} catch (IOException ioe) {
			Log.e("error", "Input/Output error :"+ioe.getMessage());
		} catch (ParserConfigurationException e) {
			Log.e("error", "Parser error :"+e.getMessage());
		}catch (SAXException e) {
			Log.e("error", "SAX error :"+e.getMessage());
		}catch (Exception e){
			Log.e("error", "Other Exception from getPage : "+e.getMessage());
		}
		return null;
	}

	@Override
	public void onPostExecute(final Week week){
		core.afterUpdateWeek(week);
	}
}
